﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using EQT.Dal;
using EQT.Model;
using System.Collections.Generic;

public partial class SelectTester : System.Web.UI.Page
{
    private DaCoTestItem dacti = DevFuture.Common.WorkContext.AppCtx.GetObject("DaCoTestItem") as DaCoTestItem;
    private DaDept dalDept = DevFuture.Common.WorkContext.AppCtx.GetObject("DaDept") as DaDept;
    private DaEmployee daemp = DevFuture.Common.WorkContext.AppCtx.GetObject("DaEmployee") as DaEmployee;
    private DaTester datester = DevFuture.Common.WorkContext.AppCtx.GetObject("DaTester") as DaTester;
    //所有试验员
    private System.Collections.Specialized.StringCollection selectedEID = new System.Collections.Specialized.StringCollection();
    //主管实验员
    private System.Collections.Specialized.StringCollection masterEID = new System.Collections.Specialized.StringCollection();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //查询字符串会给定合同检验项ID： Co_Item_ID
            string co_item_id = Request.QueryString["co_item_id"];
            ViewState["CO_ITEM_ID"] = co_item_id;
            if (!String.IsNullOrEmpty(co_item_id))
            {
                #region //查找该检验项已经设定的所有测试人员
                IList<MoEmployee> emps = daemp.GetEntities(String.Format("  inner join Tester r on Employee.Emp_ID=r.EMP_ID WHERE r.Co_Item_ID='{0}'", co_item_id));

                if (emps != null && emps.Count > 0)
                {
                    System.Text.StringBuilder sb_eid = new System.Text.StringBuilder();
                    System.Text.StringBuilder sb_ename = new System.Text.StringBuilder();
                    for (int i = 0; i < emps.Count; i++)
                    {
                        sb_eid.Append(emps[i].EmpId);
                        sb_ename.Append(emps[i].Fullname);
                        if (i < emps.Count - 1)
                        {
                            sb_eid.Append("/");
                            sb_ename.Append("/");
                        }
                    }
                    ViewState["EMP_IDS"] = sb_eid.ToString();
                    string enames = sb_ename.ToString();
                    ViewState["EMP_NAMES"] = enames;

                    LabelSelectedTester.Text = enames;
                #endregion
                    #region   //在有试验人员的情况下，才查询主管实验员
                    IList<MoEmployee> masterEmps = daemp.GetEntities(
                        String.Format("  inner join Tester r on Employee.Emp_ID=r.EMP_ID WHERE r.Co_Item_ID='{0}' AND r.Duty_Code='M'", co_item_id));
                    System.Text.StringBuilder sb_master_eid = new System.Text.StringBuilder();
                    System.Text.StringBuilder sb_master_ename = new System.Text.StringBuilder();
                    for (int i = 0; i < masterEmps.Count; i++)
                    {
                        sb_master_eid.Append(masterEmps[i].EmpId);
                        sb_master_ename.Append(masterEmps[i].Fullname);
                        if (i < masterEmps.Count - 1)
                        {
                            sb_master_eid.Append("/");
                            sb_master_ename.Append("/");
                        }
                    }
                    ViewState["MASTER_EMP_IDS"] = sb_master_eid.ToString();
                    string master_enames = sb_master_ename.ToString();
                    ViewState["MASTER_EMP_NAMES"] = master_enames;
                    LabelTestMaster.Text = master_enames;
                #endregion
                }
                else
                {
                    LabelSelectedTester.Text = "您未选定任何测试执行人员!";
                }

                DataSet dsDept = dalDept.Query(string.Empty);
                Utility.BindDataSet2Combox(dsDept, DDLdept, "Dept_Name", "Dept_ID");
                BindEmps();
            }
            else
            {
                Utility.SiteError("缺失必须的参数:co_item_id");
            }

        }
    }


    private void BindEmps()
    {
        GridViewEmp.DataSource = dacti.GetEmp4TesterSelect(ViewState["CO_ITEM_ID"].ToString(),
            DDLdept.SelectedValue);
        GridViewEmp.DataBind();
    }

    /// <summary>
    /// 选择了一批实验员，其中可能包含主管实验员
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnSelect_Click(object sender, EventArgs e)
    {
        #region 状态历史中已经选定的
        System.Collections.Specialized.StringCollection sc_eid = new System.Collections.Specialized.StringCollection();
        System.Collections.Specialized.StringCollection sc_ename = new System.Collections.Specialized.StringCollection();


        System.Collections.Specialized.StringCollection sc_master_eid = new System.Collections.Specialized.StringCollection();
        System.Collections.Specialized.StringCollection sc_master_ename = new System.Collections.Specialized.StringCollection();



        if (ViewState["EMP_IDS"] != null)
        {
            string eids = ViewState["EMP_IDS"].ToString();
            string enames = ViewState["EMP_NAMES"].ToString();

            string[] rc_ids = eids.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            string[] rc_names = enames.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            if (rc_ids != null) sc_eid.AddRange(rc_ids);
            if (rc_names != null) sc_ename.AddRange(rc_names);
        }


        if (ViewState["MASTER_EMP_IDS"] != null)
        {
            string eids = ViewState["MASTER_EMP_IDS"].ToString();
            string enames = ViewState["MASTER_EMP_NAMES"].ToString();

            string[] rc_ids = eids.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            string[] rc_names = enames.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            if (rc_ids != null) sc_master_eid.AddRange(rc_ids);
            if (rc_names != null) sc_master_ename.AddRange(rc_names);
        }

        #endregion

        #region 同步当前页面到已选定
        for (int i = 0; i <= GridViewEmp.Rows.Count - 1; i++)
        {
            #region 检验人员
            CheckBox cbox = (CheckBox)GridViewEmp.Rows[i].FindControl("CheckBox1");
            if (cbox != null)
            {

                string eid = GridViewEmp.Rows[i].Cells[1].Text;
                if (cbox.Checked)//选中了
                {
                    if (!sc_eid.Contains(eid))
                    {
                        sc_eid.Add(eid);
                        sc_ename.Add(GridViewEmp.Rows[i].Cells[2].Text);
                    }

                }
                else
                {
                    if (sc_eid.Contains(eid))//包含的话，应该清除
                    {
                        sc_ename.RemoveAt(sc_eid.IndexOf(eid));
                        sc_eid.Remove(eid);
                    }

                }
            }
            #endregion

            #region 主管实验员
            CheckBox cbox2 = (CheckBox)GridViewEmp.Rows[i].FindControl("CBIsMaster");
            if (cbox2 != null)
            {
                string eid = GridViewEmp.Rows[i].Cells[1].Text;
                if (cbox2.Checked)//选中了
                {
                    if (!sc_master_eid.Contains(eid))
                    {
                        sc_master_eid.Add(eid);
                        sc_master_ename.Add(GridViewEmp.Rows[i].Cells[2].Text);
                    }

                }
                else
                {
                    if (sc_master_eid.Contains(eid))//包含的话，应该清除
                    {
                        sc_master_ename.RemoveAt(sc_master_eid.IndexOf(eid));
                        sc_master_eid.Remove(eid);
                    }

                }
            }

        }
            #endregion

        string[] strlist1 = new string[sc_eid.Count];
        sc_eid.CopyTo(strlist1, 0);
        ViewState["EMP_IDS"] = Utility.ConvertStringListToOneRow(strlist1);

        string[] strlist2 = new string[sc_ename.Count];
        sc_ename.CopyTo(strlist2, 0);
        ViewState["EMP_NAMES"] = Utility.ConvertStringListToOneRow(strlist2);
        LabelSelectedTester.Text = ViewState["EMP_NAMES"].ToString();

        string[] strlist3 = new string[sc_master_eid.Count];
        sc_master_eid.CopyTo(strlist3, 0);
        ViewState["MASTER_EMP_IDS"] = Utility.ConvertStringListToOneRow(strlist3);

        string[] strlist4 = new string[sc_master_ename.Count];
        sc_master_ename.CopyTo(strlist4, 0);
        ViewState["MASTER_EMP_NAMES"] = Utility.ConvertStringListToOneRow(strlist4);
        LabelTestMaster.Text = ViewState["MASTER_EMP_NAMES"].ToString();


        #endregion




    }

    /// <summary>
    /// 选择完成
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnOK_Click(object sender, EventArgs e)
    {
        BtnSelect_Click(BtnSelect, e);
        //保存到数据库
        if (ViewState["EMP_IDS"] != null)
        {
            string strlist = (string)ViewState["EMP_IDS"];
            //所有选定的人的id
            string[] ss = strlist.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            string co_item_id = ViewState["CO_ITEM_ID"].ToString();
            string strlist2 = null;
            string[] mss = null;
            if (ViewState["MASTER_EMP_IDS"] != null)
            {
                strlist2 = ViewState["MASTER_EMP_IDS"].ToString();
                mss = strlist2.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            }
            UserContext context = Session["USER_CONTEXT"] as UserContext;
            //将更改保存到数据库
            if (ss != null && ss.Length > 0)
            {
                dacti.SetCoItemTester(ss, mss, co_item_id,context.UserID);
                DaActLog.LogNormalAct(User.Identity.Name, String.Format("{2}设置测试人员{0}:{1}", co_item_id, strlist,context.EmpName));
            }
            else
            {
                Utility.GlobalLog.ErrorFormat("选定的人员无效！:{0}.", ViewState["EMP_IDS"]);
            }

        }


        //回发后自动关闭        
        ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "UpdatePanel1", "window.close();", true);
    }
    protected void DDLdept_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindEmps();
    }
    protected void GridViewEmp_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView drv = e.Row.DataItem as DataRowView;
            if (drv != null)
            {
                CheckBox cb = (CheckBox)e.Row.FindControl("CheckBox1");
                string empid = drv["EMP_ID"].ToString();
                cb.Checked = ((int)drv["CHK"] > 0) || (selectedEID.Contains(empid));

                CheckBox cb2 = (CheckBox)e.Row.FindControl("CBIsMaster");
                if (drv["DUTY_CODE"] != DBNull.Value && drv["DUTY_CODE"] != null)
                {
                    cb2.Checked = ((string)drv["DUTY_CODE"] == "M") || (masterEID.Contains(empid));
                }
            }
        }
    }
}
